<?php
try {

	$content = array();


	$con = mysql_connect('localhost', 'backbone', 'backbone');
	mysql_select_db('backbone', $con);
	mysql_query("INSERT INTO log SET date=NOW(), content='GET=".json_encode($_GET)."\nPOST=".json_encode($_POST)."';");
	

	/** READ **/
	if ( $_SERVER['REQUEST_METHOD'] == "GET" ) {
		// If the ID is set, get the record with that ID
		$extra = array_key_exists('id', $_GET) ? " WHERE id = ".$_GET['id'] : null;
		$r = mysql_query("SELECT * FROM people".$extra);
						
		if ($extra) {
			// If the ID is set, fetch one record
			$content = mysql_fetch_assoc($r);
			
		}
		else {
			// Fetch all of the records if no ID is set
			for($i = mysql_num_rows($r); $i > 0 ; $i--) {
				$content[] = mysql_fetch_assoc($r);
			}
		}
		// Encode it as JSON and ship it back
		echo json_encode($content);
	}
	/** UPDATE or DELETE **/
	else if ( array_key_exists ("_method", $_POST) ) {
		
		if($_POST['_method'] == "PUT"){
		    $item=json_decode($_POST['model']);
			mysql_query("UPDATE `people` SET `name`= '".$item->name."' ,`age`= ".$item->age." WHERE `id` = ".$_GET['id'].";");
		}else if($_POST['_method'] == "DELETE"){
			$item=json_decode($_POST['model']);
			mysql_query("DELETE FROM `people` WHERE `id` = ".$_GET['id'].";");					
		}
		
	}
	/** CREATE **/
	else {
		$item=json_decode($_POST['model']);
		mysql_query("INSERT INTO `people` (`id`, `name`, `age`) VALUES (null, '".$item->name."', ".$item->age.");");
	}
	


} catch(Exception $e) {
	echo $e."\n";
}